// 预测红色连续不超过2次的group
const filterRedContinuousLimit2Group = (item) => {
  const [secondLast, last] = item.accuracy_array.slice(-2)
  return secondLast === 0 && last === 0
}

// 预测绿色回弹，红色不连续的group
const filterGreenReboundRedNonContinuousGroup = (item) => {
  const [secondLast, last] = item.accuracy_array.slice(-2)
  return secondLast === 0 && last === 1
}

// 预测绿色连续的group
const filterGreenContinuousGroup = (item) => {
  const [secondLast, last] = item.accuracy_array.slice(-2)
  return secondLast === 1 && last === 1
}

const sortResults = (a, b) => {
  if (b.accuracy_rate !== a.accuracy_rate) {
    return b.accuracy_rate - a.accuracy_rate // accuracy_rate 降序
  }
  return a.max_consecutive_incorrect - b.max_consecutive_incorrect // max_consecutive_incorrect 升序
}

// let mySet = new Set([1, 2, 3]);
// const newArray = [4, 5, 6];

// // 使用 spread 操作符扩展数组元素到 Set 中
// mySet = new Set([...mySet, ...newArray]);

// console.log(mySet);  // Set { 1, 2, 3, 4, 5, 6 }

const padArrayNumbers = (arr) => {
  return arr.map((item) => {
    // 转换为字符串并判断是否小于 10
    const str = String(item)
    return str.length < 2 ? str.padStart(2, '0') : str
  })
}

// 示例
// const arr = [5, '9', '04', 11, 3, '2'];
// console.log(padArrayNumbers(arr)); // ['05', '09', '04', '11', '03', '02']

const padSingleValue = (value) => {
  const str = String(value)
  return str.length < 2 ? str.padStart(2, '0') : str
}

// 示例
// console.log(padSingleValue(5));    // '05'
// console.log(padSingleValue('09')); // '09'
// console.log(padSingleValue(11));   // '11'
// console.log(padSingleValue('4'));  // '04'

const getLuckyArrayAndIds = (
  flatGroupMap,
  currentNumber,
  redContinuousLimit2Group,
  greenReboundRedNonContinuousGroup,
  greenContinuousGroup
) => {
  const a = redContinuousLimit2Group.map((item) => {
    return {
      ...item,
      forecast_type: 'red_continuous_limit_2'
    }
  })

  const b = greenReboundRedNonContinuousGroup.map((item) => {
    return {
      ...item,
      forecast_type: 'green_rebound_red_non_continuous'
    }
  })

  const c = greenContinuousGroup.map((item) => {
    return {
      ...item,
      forecast_type: 'green_continuous'
    }
  })

  const idsMap = {
    red_continuous_limit_2: [],
    green_rebound_red_non_continuous: [],
    green_continuous: []
  }

  // 合并排序
  const allGroups = [...a, ...b, ...c]

  // 用 Set 来避免重复的号码
  const luckySet = new Set()

  allGroups.forEach((group) => {
    const { id, group_name, sub_index, forecast_type } = group
    // idsMap[forecast_type].push(id)

    if (luckySet.size < 32) {
      const groupData = flatGroupMap[group_name][sub_index]
      // 一个号码一个号码去添加
      groupData.forEach((number) => {
        if (luckySet.size < 32) {
          luckySet.add(number)
        }
      })
      idsMap[forecast_type].push(id)
    }
  })

  // console.log('luckySet Size', luckySet.size)
  const luckyArray = [...luckySet]

  const arr = Array.from({ length: 49 }, (_, i) => i + 1).map((num) => (num < 10 ? `0${num}` : `${num}`))
  const padLuckyArray = padArrayNumbers(luckyArray)

  const killArray = arr.filter((item) => !padLuckyArray.includes(item))

  // console.log('luckyArray', luckyArray.length)
  // console.log('killArray', killArray.length)

  const accuracy = padLuckyArray.includes(padSingleValue(currentNumber)) ? 1 : 0
  console.log('accuracy', accuracy)
  return {
    red_continuous_limit_2_group_ids: JSON.stringify(idsMap.red_continuous_limit_2),
    green_rebound_red_non_continuous_group_ids: JSON.stringify(idsMap.green_rebound_red_non_continuous),
    green_continuous_group_ids: JSON.stringify(idsMap.green_continuous)
    // luckyArray: ,
    // killArray
  }

  // // 合并所有分组，按优先级顺序处理
  // const allGroups = [...a, ...b, ...c]

  // // 将 luckySet 转为数组，确保最多 32 个号码
  // const luckyArray = Array.from(luckySet).slice(0, 32)

  // return {
  //   luckyArray,
  //   red_continuous_limit_2_group_ids,
  //   green_rebound_red_non_continuous_group_ids,
  //   green_continuous_group_ids
  // }
}

const calcForecast = (flatGroupMap, itemsArrary, currentNumber) => {
  // todo cyan: filter twentyfour group

  // itemsArrary 数据结构
  // {
  //   id: 301907,
  //   history_result_id: 20,
  //   time: '2022-01-20',
  //   number: '19',
  //   group_name: 'FOUR_RANGE_00000468_GROUPS',
  //   group_type: 'four',
  //   sub_index: 6,
  //   accuracy: 0,
  //   accuracy_array: [
  //     1, 1, 1, 1, 0, 1, 0,
  //     1, 1, 1, 1, 0, 1, 1,
  //     1, 1, 1, 0, 1, 0
  //   ],
  //   correct_count: 15,
  //   incorrect_count: 5,
  //   accuracy_rate: 0.75,
  //   max_consecutive_correct: 5,
  //   max_consecutive_incorrect: 1,
  //   consecutive_correct_segments: 5,
  //   consecutive_incorrect_segments: 5,
  //   avg_consecutive_correct: 3,
  //   avg_consecutive_incorrect: 1,
  //   current_consecutive_correct: 0,
  //   current_consecutive_incorrect: 1
  // }

  // console.log('itemsArrary', itemsArrary)

  // 预测红色连续不超过2次的group
  const redContinuousLimit2Group = itemsArrary.filter(filterRedContinuousLimit2Group).sort(sortResults)
  // 预测绿色回弹，红色不连续的group
  const greenReboundRedNonContinuousGroup = itemsArrary
    .filter(filterGreenReboundRedNonContinuousGroup)
    .sort(sortResults)
  // 预测绿色连续的group
  const greenContinuousGroup = itemsArrary.filter(filterGreenContinuousGroup).sort(sortResults)

  // 预测幸运数组
  const luckyArray = []
  // 预测杀数组
  const killArray = []

  const { red_continuous_limit_2_group_ids, green_rebound_red_non_continuous_group_ids, green_continuous_group_ids } =
    getLuckyArrayAndIds(
      flatGroupMap,
      currentNumber,
      redContinuousLimit2Group,
      greenReboundRedNonContinuousGroup,
      greenContinuousGroup
    )

  return {
    red_continuous_limit_2_group_ids,
    green_rebound_red_non_continuous_group_ids,
    green_continuous_group_ids,
    // lucky_array: null,
    // kill_array: null,
    // accuracy: 1
  }
}

module.exports = { calcForecast }
